package cn.gok.utils;

import cn.gok.common.entity.backstage.Commons;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author: DxlinY
 * @apiNote: 图片上传用
 * @date: 2020/10/10
 * @time: 10:14
 */
@Slf4j
public class ImageUtil {

    /**
     * 图片上传
     *
     * @param files 图片文件集
     * @param model 当前图片属于哪个模块
     * @return 图片相对路径
     */
    public static String upload(MultipartFile[] files, String model) {
        if (files == null) return "";
        String username = UserContext.user().getUserName();
        String unityPath = username + "\\" + model + "\\" + DateUtil.nowDate();
        String absoluteRedirectPath = Commons.IMAGE_REDIRECT_PATH + unityPath + "\\";
        String redirectPath = Commons.REFERENCE_PATH_WEBAPP + unityPath + "\\";
        StringBuilder firstImagePath = new StringBuilder(redirectPath);
        boolean flag = true;
        for (MultipartFile image : files) {
            if (image != null && isImage(Objects.requireNonNull(image.getOriginalFilename()))) {
                if (flag) {
                    firstImagePath.append(image.getOriginalFilename());
                    flag = false;
                }
                File absolutePathFile = new File(absoluteRedirectPath);
                if (!absolutePathFile.exists()) {
                    absolutePathFile.mkdirs();
                }
                File storeFile = new File(absoluteRedirectPath + image.getOriginalFilename());
                try {
                    image.transferTo(storeFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("{}图片上传出错", image.getOriginalFilename());
                }
            }

        }
        return firstImagePath.toString();
    }


    public static boolean isImage(String name) {
        String reg = ".+(.jpeg|.jpg|.png|.bmp)$";
        return Pattern.matches(reg, name.toLowerCase());
    }
}
